import {goodsList,goodsCount} from '../../../util/request/api'
//封装菜单管理的状态管理
const state = {
    //菜单列表
    goodslist:[],
    size:2,
    page:1,
    count:0
}

const getters ={
    getGoodsList(state){
        return state.goodslist
    },
    getCount(state){
        return state.count
    },
    //返回pageSize
    getSize(state){
       return state.size 
    }
}

const mutations = {
    REQ_GOODSLIST(state,payload){
        state.goodslist = payload
    },
    REQ_GOODSCOUNT(state,payload){
        state.count = payload
    },
    //封装一个修改page的mutations
    REQ_CHANGEPAGE(state,payload){
        state.page=payload
    }
}

const actions ={
    // 封装一个行动用于修改菜单列表
    getGoodsAction(context){
        goodsList({
            size:context.state.size,
            page:context.state.page,
        })
        .then(res=>{
            if(res.code==200){
                context.commit('REQ_GOODSLIST',res.list)

               let list = res.list?res.list:[]
               if(context.state.page!=1&&list.length==0){
                context.dispatch('changePageAction',context.state.page-1)
               }
            }
        })
    },
    //封装一个行动用于获取管理员总数
    getCountAction(context){
        goodsCount()
        .then(res=>{
            console.log(res,'管理员总数');
            if(res.code==200){
                context.commit('REQ_GOODSCOUNT',res.list[0].total)
            }
        })
    },
    //封装一个切换页面的行动
    changePageAction(context,payload){
        console.log(payload,'payload参数');
        //修改state中的page
        context.commit('REQ_CHANGEPAGE',payload)
        //重新调用列表接口
        context.dispatch('getGoodsAction')
    }
}

export default {
    state,
    getters,
    mutations,
    actions,
    namespaced:true
}